var stationList = null;
var map = null;
var oldZoom = 0;
var ifNeedGetAll = false;
var enlargeCityId = null;
$(function () {
    getType();
    getStationCountTableData();

    map = new BMap.Map("allmap", {
        enableMapClick: false,
        minZoom: 5,
        maxZoom: 18
    });
    map.centerAndZoom("西安", 5);
    //添加鼠标滚动缩放
    map.enableScrollWheelZoom();
    //添加缩略图控件
    //map.addControl(new BMap.OverviewMapControl({isOpen:false,anchor:BMAP_ANCHOR_BOTTOM_RIGHT}));
    //添加缩放平移控件
    //map.addControl(new BMap.NavigationControl());
    //添加比例尺控件
    //map.addControl(new BMap.ScaleControl());

    //地图缩放
    map.addEventListener("zoomend", function () {
        changeMapZoom(this.getZoom());
    });

});
// 复杂的自定义覆盖物
function ComplexCustomOverlay(point, text, cityId) {
    this._point = point;
    this._text = text;
    this._cityId = cityId;
}
ComplexCustomOverlay.prototype = new BMap.Overlay();
ComplexCustomOverlay.prototype.initialize = function (mp) {
    var ppoint = this._point;
    var cityId = this._cityId;
    this._map = mp;
    var div = this._div = document.createElement("div");
    div.style.position = "absolute";
    div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
    div.style.backgroundColor = "#EE5D5B";
    div.style.border = "1px solid #999";
    div.style.borderRadius = "50%";
    div.style.color = "#000";
    div.style.width = "30px";
    div.style.height = "30px";
    div.style.textAlign = "center";
    div.style.padding = "0px";
    div.style.lineHeight = "30px";
    div.style.whiteSpace = "nowrap";
    div.style.MozUserSelect = "none";
    div.style.fontSize = "14px"
    var span = this._span = document.createElement("span");
    div.appendChild(span);
    span.appendChild(document.createTextNode(this._text));

    var arrow = this._arrow = document.createElement("div");
    arrow.style.position = "absolute";
    arrow.style.width = "11px";
    arrow.style.height = "10px";
    arrow.style.top = "0";
    arrow.style.left = "20px";
    arrow.style.overflow = "hidden";
    div.appendChild(arrow);
    div.addEventListener("click", function () {
        enlargeCityId = cityId;
        map.setCenter(ppoint);
        map.setZoom(oldZoom + 3);
    });
    map.getPanes().labelPane.appendChild(div);
    return div;
}
ComplexCustomOverlay.prototype.draw = function () {
    var map = this._map;
    var pixel = map.pointToOverlayPixel(this._point);
    this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
    this._div.style.top = pixel.y + "px";
}

function changeMapZoom(zoom) {
    $("#result_ul").html("");
    $(".search-result").hide();
    $(".search_detail").hide();

    console.log(zoom);
    if (zoom < 7) {
        if (oldZoom == 0 || oldZoom > 7) {
            showProvince();
        }
    }
    if (zoom >= 7 && zoom <= 10) {
        if (oldZoom < 7 || oldZoom > 10) {
            showCity();
        }
    }
    if (zoom > 10) {
        if (oldZoom <= 10) {
            ifNeedGetAll = true;
            showAllStations();
        }
    }
    oldZoom = zoom;
}

function showProvince() {
    map.clearOverlays();
    $.ajax({
        url: ctx + "/station/countByArea?type=province",
        data: {},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (!showMsg(data)) {
                return;
            }
            provinces = data.content;
            for (i = 0; i < provinces.length; i++) {
                var statistic = provinces[i];
                var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(statistic.latitude, statistic.longitude), statistic.totalCount);

                map.addOverlay(myCompOverlay);
            }
        }
    });
}
function showCity() {
    map.clearOverlays();
    $.ajax({
        url: ctx + "/station/countByArea?type=city",
        data: {},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (!showMsg(data)) {
                return;
            }
            citys = data.content;
            for (i = 0; i < citys.length; i++) {
                var statistic = citys[i];
                var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(statistic.latitude, statistic.longitude), statistic.totalCount, statistic.id);
                map.addOverlay(myCompOverlay);
            }
        }
    });
}
function showAllStations() {
    if (ifNeedGetAll) {
        map.clearOverlays();
        $.ajax({
            url: ctx + "/station/query",
            data: {},
            dataType: 'json',
            type: 'get',
            success: function (data) {
                if (!showMsg(data)) {
                    return;
                }
                stationList = data.content.content;
                for (i = 0; i < stationList.length; i++) {
                    var station = stationList[i];
                    if(enlargeCityId!=null){
                        if(station.cityId==enlargeCityId){
                            map.setCenter(new BMap.Point(station.latitude, station.longitude));
                            enlargeCityId=null;
                        }
                    }
                    addMarker(station, i);
                }
            }
        });
        ifNeedGetAll = false;
    }
}


function addMarker(station, index) {
    var marker = new BMap.Marker(new BMap.Point(station.latitude, station.longitude));
    var label = new BMap.Label(station.name, {offset: new BMap.Size(20, -10)});
    marker.setLabel(label);
    map.addOverlay(marker);
    marker.setLabel(label);
    marker.addEventListener("click", function () {
        detailStation(index);
    });
    var id = station.id;
    var infoWindow;
    marker.addEventListener("mouseover", function () {
        var that=this;
        $.ajax({
            url: ctx + "/equipData/now?stationId=" + id,
            data: {},
            dataType: 'json',
            type: 'get',
            success: function (data) {
                if (data.result) {
                    var content = data.content;
                    var sContent="";
                    if (content.collectionTime) {
                        var imgUrl=ctx + "/images/web/no_img.png";
                        var headPic=content.headPic;
                        if(headPic) {
                            var imgUrl = ctx + "/equipData/showFile?type=1&dataId=" + content.id;
                        }
                        sContent = '<div style="padding: 10px;"><table class="table-bordered base-table" style="width:320px;">' +
                            '<tr><td class="base-title">车头照片：</td><td><img height="60" src="'+imgUrl+'"></td></tr>' +
                            '<tr><td class="base-title">采集时间：</td><td>' + content.collectionTime + '</td></tr>' +
                            '<tr><td class="base-title">车牌号码：</td><td>' + content.plateNo + '</td></tr>' +
                            '<tr><td class="base-title">车轴数：</td><td>' + content.axleNumber + '</td></tr>' +
                            '<tr><td class="base-title">车货总重(kg)：</td><td>' + content.totalWeight + '</td></tr>' +
                            '<tr><td class="base-title">超限量(%)：</td><td>' + content.overrunWeight + '%</td></tr>' +
                            '</table></div>';
                    }else{
                        sContent = '<div style="padding: 10px;"><table class="table-bordered base-table" style="width:320px;">' +
                            '<tr><td class="" style="text-align: center">无最近记录</td></tr>' +
                            '</table></div>';
                    }
                    infoWindow = new BMap.InfoWindow(sContent);
                    that.openInfoWindow(infoWindow);
                }
            }
        })
    });
    marker.addEventListener("mouseout", function () {
        this.closeInfoWindow(infoWindow);
    });
}

/**
 * 设置显示区域下拉框
 * @param data
 */
function getType() {
    $.ajax({
            url: ctx + "/station/typeList",
            data: {},
            dataType: 'json',
            type: 'get',
            success: function (data) {
                if (!showMsg(data)) {
                    return;
                }
                $('#stationType').combobox({
                    valueField: 'id',
                    textField: 'text',
                    data: data.content,
                    panelHeight: 'auto'
                });
            }
        }
    );
}
/**
 * 站点数量统计情况
 * @param data
 */
function getStationCountTableData() {
    $.ajax({
            url: ctx + "/station/countByAreaAndOrg",
            data: {},
            dataType: 'json',
            type: 'get',
            success: function (data) {
                if (!showMsg(data)) {
                    return;
                }
                var org_level = data.org_level;
                var levelName = "";
                if (org_level == 0) {
                    levelName = "省";
                }
                if (org_level == 1) {
                    levelName = "市";
                }
                if (org_level == 2) {
                    levelName = "县";
                }
                var counts = data.content;
                var txt = "";
                for (var i = 0; i < counts.length; i++) {
                    var c = counts[i];
                    txt += '<tr><td>' + c.areaName + '</td><td>' + c.totalCount + '</td><td>' + c.typeCount1 + '</td><td>' + c.typeCount2 + '</td><td>' + c.typeCount3 + '</td><td>' + c.typeCount4 + '</td><td>' + c.typeCount5 + '</td></tr>'
                }
                $("#station-count-table").html(txt);
            }
        }
    );
}

/**
 * 搜索
 */
function stationSearch() {
    var type = $("#searchDiv").find("input[name='siteType']").val();
    var keyword = $("#keyword").val();
    var param = {
        name: keyword,
        type: type,
        page: 0,
        size: 10
    }
    $.ajax({
        url: ctx + "/station/query",
        data: param,
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (!showMsg(data)) {
                return;
            }
            ifNeedGetAll = true;
            stationList = data.content.content;

            map.clearOverlays();
            $("#result_ul").html("");
            $(".search-result").hide();
            $(".search_detail").hide();

            for (i = 0; i < stationList.length; i++) {
                var station = stationList[i];
                var order = i + 1;
                var txt = '<li>' +
                    '<a onclick="detailStation(' + i + ');">' +
                    '<span>' + order + '</span>' +
                    '<span class="station-name">' + station.name + '</span>' +
                    '<p>' + station.organName + ' ' + station.address + '</p>' +
                    '</a>' +
                    '</li>';

                $("#result_ul").append(txt);
                addMarker(station, i);
            }
            $(".search_result").show();
            $(".search_result").find(".panel").show();
        }
    });
}

var showStationId=null;
function detailStation(index) {
    selectedId = null;
    var station = stationList[index];
    showStationId=station.id;
    map.centerAndZoom(new BMap.Point(station.latitude, station.longitude), 14);
    showAllStations();
    getBaseData(station.id);
    getEquipData(station.id);
    getNowData(station.id);
    initNowDataTimer();
    getHistoryData(station.id, 0)
    $(".search_result").hide();
    $(".search_detail").show();
    $(".search_detail").find(".panel-title").html(station.name);
}
function initNowDataTimer(){
    cleanNowDataTimer();
    NowDataTimer = window.setInterval(function(){
        refreshNowData();
    },600000);
}
function refreshNowData(){
    getNowData(showStationId);
}

function getBaseData(id) {
    console.log("getBaseData");
    $.ajax({
        url: ctx + "/station/detail",
        data: {id: id},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (data.result) {
                var station = data.content;
                $("#baseCode").html(station.code);
                $("#baseName").html(station.name);
                $("#baseType").html(station.type);
                $("#baseDivision").html(station.cityName + station.districtName);
                $("#baseOrgan").html(station.organName);
                $("#baseAddress").html(station.address);
            }
        }
    })
}
function getEquipData(id) {
    console.log("getEquipData");
    $("#equip-tbody").html("");
    $.ajax({
        url: ctx + "/equip/query?stationId=" + id,
        data: {id: id, size: 100},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (data.result) {
                var equips = data.content.content;
                var txt = "";
                for (var i = 0; i < equips.length; i++) {
                    var equip = equips[i];
                    var type = equip.type;
                    if (!type) {
                        type = "";
                    }
                    var status = equip.status;
                    if (!status) {
                        status = "";
                    }
                    txt += '<tr><td>' + equip.code + '</td><td>' + equip.name + '</td><td>' + type + '</td><td>' + status + '</td></tr>';
                }
                $("#equip-tbody").html(txt);
            }
        }
    })
}
function nowDateFormat(dateString) {
    var arr1 = dateString.split(" ");
    var sdate = arr1[0].split('-');
    var result = sdate[0] + "年" + sdate[1] + "月" + sdate[2] + "日 " + arr1[1];
    return result;
}
function nowTimeFormat(dateString) {
    var arr1 = dateString.split(" ");
    var sdate = arr1[1].split(':');
    var result = sdate[0] + ":" + sdate[1];
    return result;
}
function getNowData(id) {
    console.log("getNowData");
    $("#countTime").html("");
    $("#trainCount").html("");
    $("#now-tbody").html("");
    $.ajax({
        url: ctx + "/equipData/now?stationId=" + id,
        data: {},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (data.result) {
                var content = data.content;
                var timeStr = content.countTime;
                var headPic = content.headPic;
                var timeShow = nowDateFormat(timeStr);

                $("#countTime").html(timeShow);
                $("#trainCount").html(content.trainCount);
                if (content.collectionTime == null) {
                    $("#now-tbody").html("<tr><td colspan='5'>暂无数据</td></tr>");
                    $(".now-img-td").hide();
                } else {
                    var time = nowTimeFormat(content.collectionTime);
                    $(".now-img-td").show();
                    var imgUrl=ctx + "/images/web/no_img.png";
                    if(headPic) {
                        //var imgUrl = ctx + "equipData/headPic.img?type=1&dataId=" + content.id;
                    	imgUrl = ctx + "/equipData/showFile?type=1&dataId=" + content.id;
                    }
                    
                    //imgUrl = ctx + "/equipData/showFile?type=1&dataId=20171222170930_520501_1_2_GZ00022171222170934071000";
                    $(document).find(".headpic").attr("src",imgUrl);
                    $("#now-tbody").html("<tr><td>" + content.collectionTime + "</td><td>" + content.plateNo + "</td><td>" + content.axleNumber + "</td><td>" + content.totalWeight + "</td><td>" + content.overrunWeight + "%</td></tr>");
                }
            }
        }
    })
}

function formatDatebox(value) {
    if (value == null || value == '') {
        return '';
    }
    var dt = convertDateFromString(value);
    return dt.format("hh:mm");
}

var selectedId;
var ifFirstPage = true;
function getHistoryData(id, page) {
    $("#history-tbody").html("");
    $.ajax({
        url: ctx + "/equipData/query?stationId=" + id,
        data: {page: page, size: 10},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            if (data.result) {
                var num = data.content.totalPages;
                if (selectedId != id) {
                    ifFirstPage = true;
                    $("#Pagination").pagination(num, {
                        num_edge_entries: 1, //边缘页数
                        num_display_entries: 4, //主体页数
                        callback: pageselectCallback,
                        items_per_page: 1, //每页显示1项
                        prev_text: "前一页",
                        next_text: "后一页"
                    });
                }
                selectedId = id;
                var histories = data.content.content;
                initHistoryData(histories);
            }
        }
    })
}
function pageselectCallback(page_index, jq) {
    if (!ifFirstPage) {
        getHistoryData(selectedId, page_index);
    }
    ifFirstPage = false;
    return true;
}
function initHistoryData(histories) {
    if (histories == null || histories.length == 0) {
        $("#history-tbody").html("<tr><td colspan='5'>暂无数据</td></tr>");
    } else {
        var txt = "";
        for (var i = 0; i < histories.length; i++) {
            var history = histories[i];
            var time = nowTimeFormat(history.collectionTime);
            var plateNo = history.plateNo;
            if (!plateNo) {
                plateNo = "";
            }
            var axleNumber = history.axleNumber;
            if (!axleNumber) {
                axleNumber = "";
            }
            var totalWeight = history.totalWeight;
            if (!totalWeight) {
                totalWeight = "";
            }
            var overrunWeight = history.overrunWeight;
            if (!overrunWeight) {
                overrunWeight = "";
            } else {
                overrunWeight = overrunWeight + "%";
            }
            txt += "<tr><td>" + history.collectionTime + "</td><td>" + plateNo + "</td><td>" + axleNumber + "</td><td>" + totalWeight + "</td><td>" + overrunWeight + "</td></tr>";
        }
        $("#history-tbody").html(txt);
    }
}

function showCount() {
    $(".count-panel .easyui-panel").show();
    $(".count-panel").find(".panel").show();
}

function showHeatMap() {
    $(".heat-map-panel .easyui-panel").show();
    $(".heat-map-panel").find(".panel").show();
}

$(document).ready(function () {

    cleanNowDataTimer();
    $('.search_detail .easyui-panel').panel({
        onBeforeClose: function () {
            $(".search_detail").hide();
            return false;
        }
    });

    $(document).on('click', '.station-page .heat-table input', function () {
        var type = $(this).val();
        HeatType = type;
        $('ul li span:contains("单图热力图")').parent().click();
    });
    $(document).on('click', '.station-page .heat-map-panel span:contains("多图模式")', function () {
        $('ul li span:contains("多图热力图")').parent().click();
    });
});